package cn.xfdzx.android.apps.shop.activity;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.jpeng.jptabbar.JPTabBar;
import com.jpeng.jptabbar.OnTabSelectListener;
import com.jpeng.jptabbar.anno.NorIcons;
import com.jpeng.jptabbar.anno.SeleIcons;
import com.jpeng.jptabbar.anno.Titles;
import com.luck.picture.lib.tools.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.xfdzx.android.apps.shop.BuildConfig;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.BluetoothService;
import cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrintBlueDevicSetActivity;
import cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrintPicture;
import cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrinterCommand;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseFragmentMvpActivity;
import cn.xfdzx.android.apps.shop.bean.BluePrintContentBean;
import cn.xfdzx.android.apps.shop.bean.CarCountBeen;
import cn.xfdzx.android.apps.shop.bean.LogininfoBean;
import cn.xfdzx.android.apps.shop.bean.VersionInfoBean;
import cn.xfdzx.android.apps.shop.contract.CarNumContract;
import cn.xfdzx.android.apps.shop.contract.ScrollClickListener;
import cn.xfdzx.android.apps.shop.evenbus.CarInitDataMessage;
import cn.xfdzx.android.apps.shop.evenbus.ClassInitDataMessage;
import cn.xfdzx.android.apps.shop.evenbus.CutHomeTypeMessage;
import cn.xfdzx.android.apps.shop.evenbus.FiveFragmentClickMessage;
import cn.xfdzx.android.apps.shop.evenbus.HomeFamilyMessage;
import cn.xfdzx.android.apps.shop.evenbus.HomeTypeMessage;
import cn.xfdzx.android.apps.shop.evenbus.IMloginMessage;
import cn.xfdzx.android.apps.shop.evenbus.NearShopSelectMessage;
import cn.xfdzx.android.apps.shop.evenbus.NewOrderMessage;
import cn.xfdzx.android.apps.shop.evenbus.OrderMoneyMessage;
import cn.xfdzx.android.apps.shop.evenbus.PostCarNumMessage;
import cn.xfdzx.android.apps.shop.evenbus.UpdateCarNumMessage;
import cn.xfdzx.android.apps.shop.evenbus.VideoListMessage;
import cn.xfdzx.android.apps.shop.fragment.FourFragment;
import cn.xfdzx.android.apps.shop.fragment.SixFragment;
import cn.xfdzx.android.apps.shop.fragment.ThreeFragment;
import cn.xfdzx.android.apps.shop.fragment.TwoFragment;
import cn.xfdzx.android.apps.shop.fragment.home.HomeCommunityRetailFragment;
import cn.xfdzx.android.apps.shop.fragment.home.HomeMarketPurchaseFragment;
import cn.xfdzx.android.apps.shop.jpush.LocalBroadcastManager;
import cn.xfdzx.android.apps.shop.presenter.CarNumPresenter;
import cn.xfdzx.android.apps.shop.service.DownloadService;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.ExampleUtil;
import cn.xfdzx.android.apps.shop.util.NotificationUtil;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.view.MyScrollView;
import cn.xfdzx.android.apps.shop.widget.UpdateVersionDialog;

import static cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrintBlueDevicSetActivity.MESSAGE_CONNECTION_LOST;
import static cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrintBlueDevicSetActivity.MESSAGE_DEVICE_NAME;
import static cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrintBlueDevicSetActivity.MESSAGE_READ;
import static cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrintBlueDevicSetActivity.MESSAGE_STATE_CHANGE;
import static cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrintBlueDevicSetActivity.MESSAGE_TOAST;
import static cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrintBlueDevicSetActivity.MESSAGE_WRITE;
import static cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrintBlueDevicSetActivity.TOAST;
import static cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrintBlueDevicSetActivity.printCustomerNum;
import static cn.xfdzx.android.apps.shop.activity.myshop.bluedevic.PrintSetActivity.MESSAGE_UNABLE_CONNECT;
import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;

/**
 * @author gzk
 * @date 2020/3/25
 * description：应用主界面
 */
public class MainActivity extends BaseFragmentMvpActivity<CarNumPresenter> implements CarNumContract.View {

    private static final String TAG = "MainActivity";
    @BindView(R.id.rb_main_1)
    RadioButton rbMain1;
    @BindView(R.id.rb_main_2)
    RadioButton rbMain2;
    @BindView(R.id.rb_main_3)
    RadioButton rbMain3;
    @BindView(R.id.rb_main_4)
    RadioButton rbMain4;
    @BindView(R.id.rb_main_5)
    RadioButton rbMain5;
    @BindView(R.id.tv_car_num)
    TextView tvCarNum;
    @BindView(R.id.tabbar)
    public JPTabBar tabBar;
    private List<Fragment> mFragments;
    private FragmentManager mFragmentManager;
    private int mCurrentItem = -1;

    private long mExitTime;//记录时间间隔
    private String mMoney = "", mTime = "";
    private int position = 1;


    private String channelVersion = "";//渠道版本号
    private String downloagUrl = "";
    private PackageManager packageManager;
    private PackageInfo packageInfo;
    private boolean isFirst = true;
    private String updateType = "1";//判断是否强制更新

    private static final int REQUEST_PERMISSION = 1;
    private String[] mPermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private Context mContext;
    private MessageReceiver mMessageReceiver;
    public static boolean isForeground = false;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    private MediaPlayer mediaPlayer;
    @Titles
    private static final String[] mTitleslive = {"首页", "分类", "", "购物车", "我的"};
    @NorIcons
    private static final int[] mNormalIcons = {R.drawable.icon_home_h, R.drawable.icon_classification_h, R.drawable.shape_white_3, R.drawable.icon_car_h, R.drawable.icon_my_h};

    //    @SeleIcons
    private static final int[] mSeleIcons = {R.drawable.icon_home_l, R.drawable.icon_classification_l, R.drawable.shape_white_3, R.drawable.icon_car_l, R.drawable.icon_my_l};
    //private static final int[] mSeleIconsGreen = {R.drawable.icon_home_c, R.drawable.icon_classification_c, R.drawable.shape_white_3, R.drawable.icon_car_c, R.drawable.icon_my_c};
    @SeleIcons
    private static final int[] mSeleIconsGreen = {R.drawable.icon_home_l, R.drawable.icon_classification_l, R.drawable.shape_white_3, R.drawable.icon_car_l, R.drawable.icon_my_l};
    private TextView tv_livetitle;
    private ImageView img_liveicon;
    private RelativeLayout rl_live;

    public static int TYPE_IS_RETAIL = 1;//当前下标是否在零售  1批发  0 零售
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private String lng = "";
    private String lat = "";

    private MyScrollView myScrollView;//下拉绳
    private ImageView ivToMarket;
    private MyHandler myHandler = new MyHandler(this);

    @Override
    public int getLayoutId() {
        return R.layout.activity_one;
    }

    @Override
    public void initView() {
        mContext = MainActivity.this;
        //fragment初始化
        initParams();
        //设置默认选中
        ProgressDialog.getInstance().init(this);
//测试
//         UtilsData.getPreference(this, "login").put("token", "ZjhlYjQyUyYmU3NTA0NTBlNmIyNzc1NzMxYmM=");
        //测试移动
        //  UtilsData.getPreference(this, "login").put("token", "YmQ1ZmRjMDM4ZDIxYzQwZWU3ZDI0M2QwYTU1NzMxMTM=");
//正试
//        UtilsData.getPreference(this, "login").put("token", "ZGIwM2Y4YTlhMDVmYzkwMzhjZGRlMTcyMGIyMmZiMzU=");
        APP_TOKEN = null == UtilsData.getPreference(this, "login").getString("token") ? "" : UtilsData.getPreference(this, "login").getString("token");
        EventBus.getDefault().register(this);
        registerMessageReceiver();
        if (null != getIntent().getStringExtra("from")) {
            if (getIntent().getStringExtra("from").equals("pay")) {
                Intent intent1 = new Intent(this, PaySuccessfulNewActivity.class);
                intent1.putExtra("money", mMoney);
                intent1.putExtra("time", mTime);
                startActivity(intent1);
            } else if (getIntent().getStringExtra("from").equals("pay_cancel")) {
                Intent intent1 = new Intent(this, AllOrderActivity.class);
                intent1.putExtra("from", "pay_cancel");
                startActivity(intent1);
            }
        }
//保存购物车下的坐标
        myScrollView = findViewById(R.id.zpsv_view);
        ivToMarket = findViewById(R.id.iv_to_market);

        if (TYPE_IS_RETAIL == 0) {
            ivToMarket.setImageResource(R.drawable.icon_cut_market);
        } else {
            ivToMarket.setImageResource(R.drawable.icon_cut_retail);
        }
        initOnPreDrawListener();

        mPresenter = new CarNumPresenter();
        mPresenter.attachView(this);

        fromSet(getIntent());
        mPresenter.getVersionInfo();

        if (EmptyUtil.isNotEmpty(APP_TOKEN)) {
            Map<String, Object> map = new HashMap<>();
            map.put("equipment_number", UtilsData.getPreference(this, "jpush").getString("jpushid"));
            mPresenter.getEquipmentNumber(map);
        }

        //新订单声音
        mediaPlayer = MediaPlayer.create(this, R.raw.neworder);

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // showTaskAnimDialog();
            }
        });

        initTabBarListener();
        myScrollView.setOnScrollClickListener(new ScrollClickListener() {
            @Override
            public void onScrollClick() {
                if (TYPE_IS_RETAIL == 0) {
                    //切换为批发
                    EventBus.getDefault().post(new CutHomeTypeMessage(0));
                    //通知其它界面更改状态
                    EventBus.getDefault().post(new HomeTypeMessage(1));
                } else {
                    //切换为零售
                    EventBus.getDefault().post(new CutHomeTypeMessage(1));
                    //通知其它界面更改状态
                    EventBus.getDefault().post(new HomeTypeMessage(0));
                }
                //通知显示对应的购物车数量
                EventBus.getDefault().post(new UpdateCarNumMessage());
            }
        });

    }


    public void initStart() {
        if (TYPE_IS_RETAIL == 0) {
            img_liveicon.setImageResource(R.drawable.icon_livegreen_nor);
        } else {
            img_liveicon.setImageResource(R.drawable.icon_livegreen_nor);
        }

        tv_livetitle.setTextColor(getResources().getColor(R.color.color_565656));

        position = 1;
        changeFragment(0);
        StatusBarUtil.setLightStatusBar(MainActivity.this, false, true);
        if (TYPE_IS_RETAIL == 0) {
            tabBar.getTabAtPosition(0).getIconView().setImageResource(mSeleIcons[0]);
        } else {
            tabBar.getTabAtPosition(0).getIconView().setImageResource(mSeleIconsGreen[0]);
        }
    }

    /**
     * 底部tabbar点击事件监听
     */
    private void initTabBarListener() {
        View middleView = tabBar.getMiddleView();
        tv_livetitle = middleView.findViewById(R.id.tv_livetitle);
        img_liveicon = middleView.findViewById(R.id.img_live);
        rl_live = middleView.findViewById(R.id.rl_live);

        initStart();
        /**中间直播按钮点击*/
        rl_live.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击事件被覆盖
                if (position == 3) {
                    return;
                }

                img_liveicon.setImageResource(R.drawable.icon_livegreen_nor);
                tv_livetitle.setTextColor(getResources().getColor(R.color.color_02C557));
                position = 3;
                changeFragment(2);
                EventBus.getDefault().post(new VideoListMessage(0));
                StatusBarUtil.setLightStatusBar(MainActivity.this, true, true);
                tabBar.setSelectTab(2);
            }
        });
        tabBar.setTabListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int index) {
                if (TYPE_IS_RETAIL == 0) {
                    img_liveicon.setImageResource(R.drawable.icon_livegreen_nor);
                } else {
                    img_liveicon.setImageResource(R.drawable.icon_livegreen_nor);
                }
                //img_liveicon.setImageResource(R.drawable.icon_liveyellow_nor);
                tv_livetitle.setTextColor(getResources().getColor(R.color.color_565656));
                switch (index) {
                    case 0:
                        //刷新家庭购下标
                        EventBus.getDefault().post(new HomeFamilyMessage());
                        position = 1;
                        if (TYPE_IS_RETAIL == 1) {
                            changeFragment(0);
                        } else {
                            changeFragment(5);
                        }
                        StatusBarUtil.setLightStatusBar(MainActivity.this, false, true);
                        if (TYPE_IS_RETAIL == 0) {
                            tabBar.getTabAtPosition(0).getIconView().setImageResource(mSeleIcons[0]);
                        } else {
                            tabBar.getTabAtPosition(0).getIconView().setImageResource(mSeleIconsGreen[0]);
                        }
                        break;
                    case 1:
                        tabBar.getTabAtPosition(0).getIconView().setImageResource(mNormalIcons[0]);
                        position = 2;
                        changeFragment(1);
                        EventBus.getDefault().post(new ClassInitDataMessage(1));
                        StatusBarUtil.setLightStatusBar(MainActivity.this, true, true);
                        break;
                    case 2:
                        tabBar.getTabAtPosition(0).getIconView().setImageResource(mNormalIcons[0]);
                        if (TYPE_IS_RETAIL == 0) {
                            tv_livetitle.setTextColor(getResources().getColor(R.color.color_02C557));
                            img_liveicon.setImageResource(R.drawable.icon_livegreen_sel);
                        } else {
                            tv_livetitle.setTextColor(getResources().getColor(R.color.color_02C557));
                            img_liveicon.setImageResource(R.drawable.icon_livegreen_sel);
                        }
                        //img_liveicon.setImageResource(R.drawable.icon_liveyellow_sel);
                        position = 3;
                        changeFragment(2);
                        EventBus.getDefault().post(new VideoListMessage(0));
                        StatusBarUtil.setLightStatusBar(MainActivity.this, true, true);
                        break;
                    case 3:
                        tabBar.getTabAtPosition(0).getIconView().setImageResource(mNormalIcons[0]);
                        position = 4;
                        changeFragment(3);
                        EventBus.getDefault().post(new CarInitDataMessage(TYPE_IS_RETAIL));
                        StatusBarUtil.setLightStatusBar(MainActivity.this, true, true);
                        break;
                    case 4:
                        tabBar.getTabAtPosition(0).getIconView().setImageResource(mNormalIcons[0]);
                        position = 5;
                        changeFragment(4);
                        StatusBarUtil.setLightStatusBar(MainActivity.this, false, true);
                        EventBus.getDefault().post(new FiveFragmentClickMessage(0));
                        break;
                }
            }

            @Override
            public boolean onInterruptSelect(int index) {
                return false;
            }

        });

        getLocation();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mLocationClient != null) {
            //停止定位后，本地定位服务并不会被销毁
            mLocationClient.stopLocation();
        }
    }

    public void getLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(this);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //允许模拟定位
        mLocationOption.setMockEnable(true);
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        if (null != mLocationClient) {
            mLocationClient.setLocationOption(mLocationOption);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取最近3s内精度最高的一次定位结果：
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
//        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
//        mLocationClient.onDestroy();
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (!isGpsEnabled(mContext)) {
                Utils.toastMessage(mContext, "未开启GPS");
                //通知请求附近数据
                EventBus.getDefault().post(new NearShopSelectMessage(1));
//                Log.e("这里是未开启GPS", "");
            } else {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        //可在其中解析amapLocation获取相应内容。
                        lng = aMapLocation.getLongitude() + "";
                        lat = aMapLocation.getLatitude() + "";
                        UtilsData.getPreference(mContext, "coordinates").put("coordinates_lng", lng);
                        UtilsData.getPreference(mContext, "coordinates").put("coordinates_lat", lat);
                        Log.e("定位", aMapLocation.getProvider() + ", "
                                + aMapLocation.getCity() + ", " + aMapLocation.getDistrict());
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
//                    locationTv.setText("定位失败");
                    }
                    //通知请求附近数据
                    EventBus.getDefault().post(new NearShopSelectMessage(1));
                }
            }
        }
    };

    //判断GPS是否开启
    private boolean isGpsEnabled(Context context) {
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        // 判断GPS模块是否开启
        return locationManager != null && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    private void saveCarPosition() {
        int endPosition[] = new int[2];
        tvCarNum.getLocationInWindow(endPosition);
        UtilsData.getPreference(this, "main_car").put("tv_car_position_left", endPosition[0]);
        UtilsData.getPreference(this, "main_car").put("tv_car_position_right", endPosition[1]);
    }

    /*
     * 方法名：initOnPreDrawListener()
     * 功    能：初始化viewTreeObserver事件监听,重写OnPreDrawListener获取组件高度
     * 参    数：无
     * 返回值：无
     */
    private void initOnPreDrawListener() {
        final ViewTreeObserver viewTreeObserver = this.getWindow().getDecorView().getViewTreeObserver();
        viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                saveCarPosition();
                // 移除OnPreDrawListener事件监听
                getWindow().getDecorView().getViewTreeObserver().removeOnPreDrawListener(this);


                return true;
            }
        });
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onError(Throwable throwable) {
        Log.e("onError", throwable.toString() + "");
    }


    @Override
    public void onCarNumSuccess(CarCountBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            //保存首页购物车数量
            UtilsData.getPreference(this, "carCount").put("car_ls_count", bean.getData().getCount().getLscount());
            UtilsData.getPreference(this, "carCount").put("car_pf_count", bean.getData().getCount().getPfcount());
            if (TYPE_IS_RETAIL == 0) {
                if (bean.getData().getCount().getLscount() == 0) {
                    //tvCarNum.setVisibility(View.GONE);
                    tabBar.hideBadge(3);
                } else {
                    tabBar.showBadge(3, bean.getData().getCount().getLscount() + "");
                    //tvCarNum.setVisibility(View.VISIBLE);
                }

                //tvCarNum.setText(bean.getData().getCount().getLscount() + "");
            } else {
                if (bean.getData().getCount().getPfcount() == 0) {
                    //tvCarNum.setVisibility(View.GONE);
                    tabBar.hideBadge(3);
                } else {
                    tabBar.showBadge(3, bean.getData().getCount().getPfcount() + "");
                    //tvCarNum.setVisibility(View.VISIBLE);
                }
                //tvCarNum.setText(bean.getData().getCount().getPfcount() + "");

            }
        }
    }

    /**
     * IM登录成功
     **/
    @Override
    public void getLiveImLoginSuccess(LogininfoBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            UtilsData.getPreference(this, "IMlogin").put("IMAccount", bean.getData().getUid() == null ? "" : bean.getData().getUid());
            UtilsData.getPreference(this, "IMlogin").put("IMSign", bean.getData().getUsersig());

            Log.e("LogininfoBean", bean.getData().getUid() == null ? "" : bean.getData().getUid() + "--IMid和sign---" + bean.getData().getUsersig());
        }
    }

    @Override
    public void onVersionInfoSuccess(VersionInfoBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            Log.e("androidVersionNum", getChannelName() + "--------");
            Log.e("androidVersionNum", BuildConfig.FLAVOR + "--------");
            if (EmptyUtil.isNotEmpty(bean.getData().getUpdateType())) {
                updateType = bean.getData().getUpdateType();
            }

            downloagUrl = bean.getData().getDownloadUrl();
            if (getChannelName().equals("official")) {//官方包更新
                channelVersion = bean.getData().getZhangxian();
                updateMethod(channelVersion);
            } else {//渠道包更新
                if (getChannelName().equals("huawei")) {
                    channelVersion = bean.getData().getHuawei();
                } else if (getChannelName().equals("yingyongbao")) {
                    channelVersion = bean.getData().getYingyongbao();
                } else if (getChannelName().equals("vivo")) {
                    channelVersion = bean.getData().getVivo();
                } else if (getChannelName().equals("oppo")) {
                    channelVersion = bean.getData().getOppo();
                } else if (getChannelName().equals("xiaomi")) {
                    channelVersion = bean.getData().getXiaomi();
                }

                updateMethod(channelVersion);
            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onEquipmentNumberSuccess(VersionInfoBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {

        }
    }

    /**
     * 获取蓝牙打印信息成功
     */
    @Override
    public void getPrintingContentSuccess(BluePrintContentBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            //bluetoothPrintTests(bean.getData().getContent());

            if (EmptyUtil.isNotEmpty(UtilsData.getPreference(this, "login").getString("storetype"))) {
                if (UtilsData.getPreference(this, "login").getString("storetype").equals("0")) {

                } else {
                    if (PrintBlueDevicSetActivity.printFenJianNum == 1) {
                        createImage(bean.getData().getContent(),
                                bean.getData().getQr_code_str(),
                                bean.getData().getType());
                    } else if (PrintBlueDevicSetActivity.printFenJianNum > 1) {
                        for (int i = 0; i < PrintBlueDevicSetActivity.printFenJianNum; i++) {
                            createImage(bean.getData().getContent(),
                                    bean.getData().getQr_code_str(),
                                    bean.getData().getType());
                        }
                    }
                }

            }


            if (PrintBlueDevicSetActivity.printCustomerNum == 1) {
                createImage(bean.getData().getContent(),
                        bean.getData().getQr_code_str(),
                        bean.getData().getType());
            } else if (printCustomerNum > 1) {
                for (int i = 0; i < printCustomerNum; i++) {
                    createImage(bean.getData().getContent(),
                            bean.getData().getQr_code_str(),
                            bean.getData().getType());
                }
            }

        }
    }


    protected void initParams() {
        //注意fragments数量和radioBtn数量要对应
        mFragments = new ArrayList<>();
        mFragments.add(HomeMarketPurchaseFragment.newInstance());//批发

//        mFragments.add(OneFragment.newInstance(1));//首页
        mFragments.add(TwoFragment.newInstance(1));//分类
        mFragments.add(ThreeFragment.newInstance(1));//直播
        mFragments.add(FourFragment.newInstance(1));//购物车
        mFragments.add(SixFragment.newInstance(1));//我的
       // mFragments.add(HomeCommunityRetailFragment.newInstance());//社区零售

        mFragmentManager = getSupportFragmentManager();
    }

    /**
     * 切换fragment
     *
     * @param i
     */
    private void changeFragment(int i) {
        if (i == 0 || i == 5) {
            myScrollView.setVisibility(View.VISIBLE);
        } else {
            myScrollView.setVisibility(View.GONE);
        }

        Log.i("TAG", "i:" + i + " mCurrentItem:" + mCurrentItem);
        if (mCurrentItem == i) return; //若选中的item为当前，返回
        //这里不推荐使用replace()
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        if (mFragments.get(i).isAdded()) {
            if (mCurrentItem == 0 && i == 5 || mCurrentItem == 5 && i == 0) {
                fragmentTransaction.setCustomAnimations(R.anim.fragment_from_left, R.anim.fragment_out_right).hide(mFragments.get(mCurrentItem)).show(mFragments.get(i));
            } else {
                fragmentTransaction.hide(mFragments.get(mCurrentItem)).show(mFragments.get(i));
            }
        } else {
            if (mCurrentItem == -1) {//初始状态新建
                if (mCurrentItem == 0 && i == 5 || mCurrentItem == 5 && i == 0) {
                    fragmentTransaction.setCustomAnimations(R.anim.fragment_from_left, R.anim.fragment_out_right).add(R.id.fragment_content, mFragments.get(i));
                } else {
                    fragmentTransaction.add(R.id.fragment_content, mFragments.get(i));
                }
            } else {//非初始状态切换
                if (mCurrentItem == 0 && i == 5 || mCurrentItem == 5 && i == 0) {
                    fragmentTransaction.setCustomAnimations(R.anim.fragment_from_left, R.anim.fragment_out_right).hide(mFragments.get(mCurrentItem)).add(R.id.fragment_content, mFragments.get(i));
                } else {
                    fragmentTransaction.hide(mFragments.get(mCurrentItem)).add(R.id.fragment_content, mFragments.get(i));
                }
            }
        }
        fragmentTransaction.commit();
        mCurrentItem = i;
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void XXXXX(CutHomeTypeMessage messageEvent) {
        if (messageEvent.getMessage() == 0) {
            TYPE_IS_RETAIL = 1;
            //  setBottom(true);
            changeFragment(0);
            tabBar.setNormalIcons(mNormalIcons).setSelectedIcons(mSeleIconsGreen);
            tabBar.setSelectedColor(getResources().getColor(R.color.color_02C557));
            tabBar.getSelectedTab().setTitle("首页");
            // tabBar.getSelectedTab().setSelectIcon(R.drawable.icon_home_l);
            tabBar.getSelectedTab().getIconView().setImageResource(mSeleIconsGreen[0]);
            img_liveicon.setImageResource(R.drawable.icon_livegreen_nor);


        } else {
            TYPE_IS_RETAIL = 0;
            //  setBottom(false);
            changeFragment(5);


            tabBar.setNormalIcons(mNormalIcons).setSelectedIcons(mSeleIcons);
            tabBar.setSelectedColor(getResources().getColor(R.color.color_02C557));
            tabBar.getSelectedTab().setTitle("首页");
            tabBar.getSelectedTab().setSelectIcon(mSeleIcons[0]);
            img_liveicon.setImageResource(R.drawable.icon_livegreen_nor);
            tabBar.getSelectedTab().getIconView().setImageResource(mSeleIcons[0]);
        }
        myHandler.sendEmptyMessageDelayed(1, 1000);

    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void XXXX(UpdateCarNumMessage messageEvent) {
        if (TYPE_IS_RETAIL == 0) {
            //查询购物车数量
            int num = UtilsData.getPreference(this, "carCount").getInteger("car_ls_count");
            if (num <= 0) {
                tvCarNum.setVisibility(View.INVISIBLE);
                tabBar.hideBadge(3);
            } else {
                //tvCarNum.setVisibility(View.VISIBLE);
                tabBar.showBadge(3, num + "");
            }
            //tvCarNum.setText(num + "");
        } else {
            int num = UtilsData.getPreference(this, "carCount").getInteger("car_pf_count");
            if (num <= 0) {
                tvCarNum.setVisibility(View.INVISIBLE);
                tabBar.hideBadge(3);
            } else {
                tabBar.showBadge(3, num + "");
                //tvCarNum.setVisibility(View.VISIBLE);
            }
            // tvCarNum.setText(num + "");
        }
    }

    //网络请求刷新购物车数据
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void XXXXX(PostCarNumMessage messageEvent) {
        mPresenter.carNum("1", "");
    }

    //新订单通知
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void XXXXX(NewOrderMessage messageEvent) {
        Log.e("messageEvent", "messageEvent");
        switch (messageEvent.getOrderMessageBean().getType()) {
            case "1":
                mediaPlayer = MediaPlayer.create(this, R.raw.neworder);
                mediaPlayer.start();
                break;
            case "2":
                mediaPlayer = MediaPlayer.create(this, R.raw.ordercancle);
                mediaPlayer.start();
                break;
            case "3":
                break;
            case "4":
                break;
            case "-1":
                Log.e("messageEvent", "-1-1-1-1");
                mPresenter.getPrintingContent(messageEvent.getOrderMessageBean().getOrder_id());
                // Toast.makeText(this,"messageEvent",Toast.LENGTH_SHORT);
                Log.e("messageEvent", messageEvent.getOrderMessageBean().getOrder_id() + "===");
                break;
        }

        Log.e("messageEvent", NotificationUtil.isNotifyEnabled(this) + "---");
        if (NotificationUtil.isNotifyEnabled(this)) {

        } else {

            Intent localIntent = new Intent();
            //直接跳转到应用通知设置的代码：
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0及以上
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", getPackageName(), null));
            } else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0以上到8.0以下
                localIntent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                localIntent.putExtra("app_package", getPackageName());
                localIntent.putExtra("app_uid", getApplicationInfo().uid);
            } else if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {//4.4
                localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                localIntent.addCategory(Intent.CATEGORY_DEFAULT);
                localIntent.setData(Uri.parse("package:" + getPackageName()));
            } else {
                //4.4以下没有从app跳转到应用通知设置页面的Action，可考虑跳转到应用详情页面,
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT >= 9) {
                    localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                } else if (Build.VERSION.SDK_INT <= 8) {
                    localIntent.setAction(Intent.ACTION_VIEW);
                    localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                    localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
                }
            }
            // startActivity(localIntent);
//            Message message = new Message();
//            message.what = 1;
//            new MyHandler(this).handleMessage(message);
        }
    }

    private void bluetoothPrintTests(String msg) {
        mService = BluetoothService.getInstance(this, mHandler);
        // mService.setState(BluetoothService.STATE_CONNECTED);
        // String msg = "当前时间2020-09-04 13:42:54\n送至-新发地掌鲜分拣中心\n***#3-1-1掌鲜***\n名酒城水果蔬菜新发地临时交易区\n--------------------------------\n下单时间:1970-01-01 08:00:00\n入库时间:\n商家电话:\n--------------------------------\n品名/规格                 数量\n--------------------------------\nL600小西瓜包甜 1          0.01  3-4斤3.00斤   \n--------------------------------\n总数量                       1\n总重量(斤)                   3\n--------------------------------\n送货地点：新发地百舸湾公司院内\n联系电话：18356036228\n备注：\n\n***完 新发地掌鲜***\n";
        SendDataString(msg);
    }

    //QRcode
    private static final int QR_WIDTH = 350;
    private static final int QR_HEIGHT = 350;

    /*
     * 生成QR图
     */
    private void createImage(String testContent, String qrCode, int type) {
        mService = BluetoothService.getInstance(this, mHandler);
        try {
            // 需要引入zxing包
            QRCodeWriter writer = new QRCodeWriter();

            //String qrCode = "https://www.xfdzx.cn/";

            if (qrCode == null || "".equals(qrCode) || qrCode.length() < 1) {
                Toast.makeText(this, getText(R.string.empty), Toast.LENGTH_SHORT).show();
                return;
            }

            // 把输入的文本转为二维码
            BitMatrix martix = null;
            try {
                martix = writer.encode(qrCode, BarcodeFormat.QR_CODE,
                        QR_WIDTH, QR_HEIGHT);
            } catch (WriterException e) {
                e.printStackTrace();
            }

            System.out.println("w:" + martix.getWidth() + "h:"
                    + martix.getHeight());

            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new QRCodeWriter().encode(qrCode,
                    BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            for (int y = 0; y < QR_HEIGHT; y++) {
                for (int x = 0; x < QR_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    } else {
                        pixels[y * QR_WIDTH + x] = 0xffffffff;
                    }

                }
            }

            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
                    Bitmap.Config.ARGB_8888);

            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);

            byte[] data = PrintPicture.POS_PrintBMP(bitmap, 384, 0);
            String msg = "顾客联!\n\n";
            if (type == 0) {
                msg = "顾客联!\n\n";
            } else {
                msg = "分拣联!\n\n";
            }

            SendDataByte(PrinterCommand.POS_Print_Text(msg, "GBK", 0, 1, 1, 0));
            SendDataByte(PrinterCommand.POS_Print_Text(testContent, "GBK", 0, 0, 0, 0));
            SendDataByte(data);
            // SendDataByte(PrinterCommand.POS_Set_PrtAndFeedPaper(30));
            SendDataByte(PrinterCommand.POS_Set_Cut(1));
            SendDataByte(PrinterCommand.POS_Set_PrtInit());
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    /*
     *SendDataByte
     */
    private void SendDataByte(byte[] data) {

        if (mService.getState() != BluetoothService.STATE_CONNECTED) {
            Toast.makeText(this, "请连接蓝牙打印机", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        mService.write(data);
    }

    /****************************************************************************************************/
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothService.STATE_CONNECTED://连接成功
                            Log.e("BluetoothService", "连接成功");

                            break;
                        case BluetoothService.STATE_CONNECTING://连接中
                            Log.e("BluetoothService", "连接中");
                            break;
                        case BluetoothService.STATE_LISTEN:
                        case BluetoothService.STATE_NONE://未连接
                            Log.e("BluetoothService", "未连接");
                            break;
                    }
                    break;
                case MESSAGE_WRITE:
                    Log.e("BluetoothService", "MESSAGE_WRITE");
                    break;
                case MESSAGE_READ:
                    Log.e("BluetoothService", "MESSAGE_READ");
                    break;
                case MESSAGE_DEVICE_NAME:
                    // save the connected device's name

                    break;
                case MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(),
                            msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
                            .show();
                    break;
                case MESSAGE_CONNECTION_LOST:    //蓝牙已断开连接
                    Toast.makeText(getApplicationContext(), "蓝牙已断开连接",
                            Toast.LENGTH_SHORT).show();

                    // tv_collection.setText("已断开");
                    break;
                case MESSAGE_UNABLE_CONNECT:     //无法连接设备
                    Toast.makeText(getApplicationContext(), "无法连接设备，请重启机器稍后再试",
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private BluetoothService mService = null;

    private void SendDataString(String data) {
        if (mService.getState() != BluetoothService.STATE_CONNECTED) {
            return;
        }
        if (data.length() > 0) {
            try {
                mService.write(data.getBytes("GBK"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(this, "打印机连接异常，打印失败", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    //用户登录成功之后网络请求IM登录
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onImLogin(IMloginMessage messageEvent) {
        Log.e("LogininfoBean", messageEvent.getMessage() + "------");
        // mPresenter.getLiveImLogin(messageEvent.getMessage()+"");
        Map<String, Object> map = new HashMap<>();
        map.put("equipment_number", UtilsData.getPreference(this, "jpush").getString("jpushid"));
        mPresenter.getEquipmentNumber(map);
    }

    @Override
    public void onBackPressed() {
//        if (rbMain0.isChecked()) {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(this, R.string.pressing_again_will_exit_the_application, Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
        }
//        } else {
//            rbMain0.setChecked(true);
//        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void XXX(OrderMoneyMessage orderMoneyMessage) {
        mMoney = orderMoneyMessage.getMoney();
        mTime = orderMoneyMessage.getTime();
    }

    @Override
    protected void onDestroy() {
        if (mLocationClient != null) {
            //销毁定位客户端，同时销毁本地定位服务。
            mLocationClient.onDestroy();
        }
        if (mFragments != null) {
            mFragments.clear();
            mFragments = null;
        }
        TYPE_IS_RETAIL = 0;
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        myHandler.removeCallbacksAndMessages(null);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        if (mediaPlayer != null) {
            mediaPlayer = null;
        }
        super.onDestroy();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        fromSet(intent);
    }

    private void fromSet(Intent intent) {
        if (null != intent.getStringExtra("from")) {
            //来自支付
            if (intent.getStringExtra("from").equals("pay")) {
                //跳转新的支付成功页面
                Intent intent1 = new Intent(this, PaySuccessfulNewActivity.class);
                intent1.putExtra("money", mMoney);
                intent1.putExtra("time", mTime);
                startActivity(intent1);
            } else if (intent.getStringExtra("from").equals("pay_cancel")) {
                //来自取消支付
                Intent intent1 = new Intent(this, AllOrderActivity.class);
                intent1.putExtra("from", "pay_cancel");
                startActivity(intent1);
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (TYPE_IS_RETAIL == 0) {
            int num = UtilsData.getPreference(this, "carCount").getInteger("car_ls_count");
            if (num == 0) {
                //tvCarNum.setVisibility(View.GONE);
                tabBar.hideBadge(3);
            } else {
                //tvCarNum.setVisibility(View.VISIBLE);
                tabBar.showBadge(3, num + "");
            }
            //tvCarNum.setText(num + "");
            //刷新家庭购下标
            EventBus.getDefault().post(new HomeFamilyMessage());
        } else {
            int num = UtilsData.getPreference(this, "carCount").getInteger("car_pf_count");
            if (num == 0) {
                //tvCarNum.setVisibility(View.GONE);
                tabBar.hideBadge(3);
            } else {
                //tvCarNum.setVisibility(View.VISIBLE);
                tabBar.showBadge(3, num + "");
            }
            //tvCarNum.setText(num + "");
        }
        //请求购物车显示数量
        mPresenter.carNum("1", "");
    }

    /**
     * 版本更新的方法
     */
    private void updateMethod(String androidVersionNum) {
        if (EmptyUtil.isEmpty(androidVersionNum)) {
            return;
        }

        //如果检测本程序的版本号小于服务器的版本号，那么提示用户更新
        packageManager = this.getPackageManager();
//        String versionName = "";
        try {
            packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            Log.e("androidVersionNum", androidVersionNum + "----------");
            String[] split1 = androidVersionNum.split("\\.");  //以.分隔需要转义
            if (null != split1) {

                int serverversion = Integer.parseInt(split1[0]) * 100 + Integer.parseInt(split1[1]) * 10 + Integer.parseInt(split1[2]);
                if (isFirst && serverversion > packageInfo.versionCode) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        ActivityCompat.requestPermissions(this, mPermission, REQUEST_PERMISSION);
                    }
//                    showUpdateDialog(this,androidVersionNum,"为了更好的体验，请您更新版本～",updateType);

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_PERMISSION:
                //权限
                boolean permission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if (!permission) {
                    Toast.makeText(this, "请前往设置给予存储权限", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    showUpdateDialog(this, channelVersion, "为了更好的体验，请您更新版本～", updateType);

                }
                break;
        }
    }

    /***
     * 版本更新弹出框
     */
    UpdateVersionDialog updateVersionDialog;
    private static long time;

    public void showUpdateDialog(Activity context, String versionName, String updateDes,
                                 String updateType) {
        isFirst = false;
        if (updateVersionDialog == null) {
            updateVersionDialog = new UpdateVersionDialog(context, versionName, updateDes, updateType);
        }
        updateVersionDialog.show();

        updateVersionDialog.setClicklistener(new UpdateVersionDialog.OnListenerInterface() {
            @Override
            public void doConfirm() {
                //   Log.e("getChannel",SharedPreferencesManager.getChannel()+"===");
                if (getChannelName().equals("huawei")) {
                    toMarket(context, "cn.xfdzx.android.apps.shop", "com.huawei.appmarket");
                } else if (getChannelName().equals("oppo")) {
                    toMarket(context, "cn.xfdzx.android.apps.shop", "com.oppo.market");
                } else if (getChannelName().equals("vivo")) {
                    toMarket(context, "cn.xfdzx.android.apps.shop", "com.bbk.appstore");
                } else if (getChannelName().equals("yingyongbao")) {
                    toMarket(context, "cn.xfdzx.android.apps.shop", "com.tencent.android.qqdownloader");
                } else if (getChannelName().equals("xiaomi")) {
                    toMarket(context, "cn.xfdzx.android.apps.shop", "com.xiaomi.market");
                } else {
                    //ToastUtil.showShortToast("没有找到您手机当前版本对应的应用市场，请下载应用宝商店更新");
                    if (EmptyUtil.isNotEmpty(downloagUrl)) {
//                        loadNewVersionProgress(downloagUrl);
                        Intent intent = new Intent(mContext, DownloadService.class);
                        intent.putExtra("url", downloagUrl);
                        mContext.startService(intent);
                        Toast.makeText(mContext, "后台更新下载中...", Toast.LENGTH_SHORT).show();

                    } else {
                        ToastUtils.s(context, "当前官方渠道下载人数过多，建议到应用宝商店下载哦");
                    }
                }

                updateVersionDialog.dismiss();
            }

            @Override
            public void doCancel() {
                if (updateType.equals("2")) {
                    ToastUtils.s(context, "为了您正常使用，请您立即更新");
                    return;
                } else {
                    updateVersionDialog.dismiss();
                }

            }
        });

        updateVersionDialog.setOnKeyListener(keylistener);
    }

    DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                if (updateType.equals("1")) {//强制更新
                    ToastUtils.s(MainActivity.this, "请立即更新，否则将无法正常使用");
                    return true;
                }
                return false;
            } else {
                return false;
            }
        }
    };
    //跳转到指定应用商店，这里以华为为例

    /**
     * 跳转应用商店.
     *
     * @param context   {@link Activity}
     * @param appPkg    包名
     * @param marketPkg 应用商店包名
     * @return {@code true} 跳转成功 <br> {@code false} 跳转失败
     */
    public boolean toMarket(Activity context, String appPkg, String marketPkg) {
        Uri uri = Uri.parse("market://details?id=" + appPkg);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (marketPkg != null) {// 如果没给市场的包名，则系统会弹出市场的列表让你进行选择。
            intent.setPackage(marketPkg);
        }
        try {
            context.startActivity(intent);
            return true;
        } catch (Exception ex) {
            //loadNewVersionProgress(downUrl);
            ToastUtils.s(context, "请确认您的手机是否存在该app的下载商店，更新失败，请到应用宝商店重新下载即可～");
            ex.printStackTrace();
            return false;
        }
    }

    /**
     * 获取渠道名
     *
     * @return 如果没有获取成功，那么返回值为空
     */
    public String getChannelName() {
        if (this == null) {
            return null;
        }
        String channelName = null;
        try {
            PackageManager packageManager = getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                ApplicationInfo applicationInfo = packageManager.
                        getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        channelName = String.valueOf(applicationInfo.metaData.get("UMENG_CHANNEL"));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return channelName;
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    setCostomMsg(showMsg.toString());
                }
            } catch (Exception e) {
            }
        }
    }

    private void setCostomMsg(String msg) {
        Utils.toastMessage(this, msg);
//        if (null != msgText) {
//            msgText.setText(msg);
//            msgText.setVisibility(android.view.View.VISIBLE);
//        }
    }

    class MyHandler extends Handler {
        WeakReference<Activity> mWeakReference;

        public MyHandler(Activity activity) {
            mWeakReference = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final Activity activity = mWeakReference.get();
            if (activity != null) {
                if (msg.what == 1) {
                    if (TYPE_IS_RETAIL == 0) {
                        ivToMarket.setImageResource(R.drawable.icon_cut_market);
                    } else {
                        ivToMarket.setImageResource(R.drawable.icon_cut_retail);
                    }
                }
            }
        }
    }


    /**
     * @param outState 防止app 崩溃  碎片错乱
     */
    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);

    }
}
